/*
 * DialogRequestHandler.java
 * This file contains Boeing intellectual property. It
 * may contain information about Boeing processes that are part of the Company's
 * competitive advantage. Release of this file requires prior approval from
 * Luxoft Management. Copyright (c) 2008, The Boeing Company All Rights Reserved
 */
package chain;

import filter.ConversationManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author dakhoa
 * @version 1.0
 */
public class DialogRequestHandler extends AbstractRequestHandlerCommand {

    public static final String HANDLE_DIALOG = "_dialog";
    public static final String HANDLE_DIALOG_OPEN = "_open";
    public static final String HANDLE_DIALOG_CLOSE = "_closed";
    public static final String DIALOG_FLOW_ID = "_dialogFlowId";
    private EDATContext ctx;

    @Override
    public boolean execute(EDATContext ctx) throws Exception {
        this.ctx = ctx;
        String handleDialog = ctx.getRequest().getParameter(HANDLE_DIALOG);

        if (HANDLE_DIALOG_OPEN.equalsIgnoreCase(handleDialog)) {
            ifHandlingDialogOpen();
            return PROCESSING_COMPLETE;

        } else if (HANDLE_DIALOG_CLOSE.equalsIgnoreCase(handleDialog)) {
            handlingDialogClose();
        }

        return CONTINUE_PROCESSING;
    }

    private void handlingDialogClose() {
        String dialogFlowId = ctx.getRequest().getParameter(DIALOG_FLOW_ID);
        Map dialogFlScope = ConversationManager.getInstance().getFlowScope(dialogFlowId);
        Map dialogFlScopeCopied = new HashMap(dialogFlScope);
        dialogFlScopeCopied.remove(dialogFlowId);

        if (dialogFlowId != null) {
            ctx.getDialogEventHandler().handleDialogClose(
                dialogFlScopeCopied);
        }

        ConversationManager.getInstance().disposeFlowScope(dialogFlScope);
    }

    private void ifHandlingDialogOpen() throws IOException {
        PrintWriter writer = ctx.getResponse().getWriter();
        Map<String, Object> dialogData = new HashMap<String, Object>();
        List<String> errs = new ArrayList<String>();


        if (ctx.getDialogEventHandler().handleDialogOpen(dialogData, errs)) {
            Map<String, Object> fls = ConversationManager.getInstance().getFlowScope(true);
            fls.putAll(dialogData);
            writer.write((String) fls.get(ConversationManager.FLOW_ID));

        } else {
            writer.write("ERROR#");
            for (String e : errs) {
                writer.write(e + "#");
            }
        }

        writer.flush();
        writer.close();


    }
}
